<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '编辑任务',
  },
}
</route>
<template>
  <view class="task-edit-page">
    <!-- 自定义导航栏 -->
    <view
      class="custom-nav-bar"
      :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
    >
      <view class="nav-left">
        <text class="nav-icon i-fa-solid:chevron-left" @click="goBack"></text>
        <text class="nav-title">{{ isEdit ? '编辑任务' : '新建任务' }}</text>
      </view>
      <view class="nav-right">
        <text 
          class="nav-save" 
          :class="{ 'nav-disabled': loading }" 
          @click="loading ? null : saveTask()"
        >
          {{ loading ? '保存中...' : '保存' }}
        </text>
      </view>
    </view>

    <!-- 表单内容 -->
    <scroll-view scroll-y class="task-edit-content">
      <!-- 任务标题 -->
      <view class="form-item">
        <text class="form-label">标题</text>
        <input type="text" class="form-input" placeholder="请输入任务标题" v-model="task.title" />
      </view>

      <!-- 任务分类 -->
      <view class="form-item" @click="showCategorySelector = true">
        <text class="form-label">分类</text>
        <view class="form-value">
          <view v-if="task.category" class="category-tag" :style="{
            backgroundColor: getCategoryBgColor(task.category),
            color: getCategoryColor(task.category)
          }">
            {{ task.category }}
          </view>
          <text v-else class="placeholder-text">请选择分类</text>
          <text class="form-arrow i-fa-solid:chevron-right"></text>
        </view>
      </view>

      <!-- 优先级 -->
      <view class="form-item" @click="showPrioritySelector = true">
        <text class="form-label">优先级</text>
        <view class="form-value">
          <view class="priority-item">
            <view class="priority-dot" :class="{
              'priority-high': task.priority === 'high',
              'priority-medium': task.priority === 'medium',
              'priority-low': task.priority === 'low'
            }"></view>
            <text class="priority-text">{{ getPriorityText(task.priority) }}</text>
          </view>
          <text class="form-arrow i-fa-solid:chevron-right"></text>
        </view>
      </view>

      <!-- 截止日期 -->
      <view class="form-item" @click="showDatePicker = true">
        <text class="form-label">日期</text>
        <view class="form-value">
          <text v-if="task.date" class="date-text">{{ task.date }}</text>
          <text v-else class="placeholder-text">请选择日期</text>
          <text class="form-arrow i-fa-solid:chevron-right"></text>
        </view>
      </view>

      <!-- 时间范围 -->
      <view class="form-item" @click="showTimePicker = true">
        <text class="form-label">时间</text>
        <view class="form-value">
          <text v-if="task.timeRange" class="time-text">{{ task.timeRange }}</text>
          <text v-else class="placeholder-text">请选择时间</text>
          <text class="form-arrow i-fa-solid:chevron-right"></text>
        </view>
      </view>

      <!-- 提醒 -->
      <view class="form-item">
        <text class="form-label">提醒</text>
        <view class="form-value">
          <switch :checked="task.reminder" @change="toggleReminder" color="#007aff" />
        </view>
      </view>

      <!-- 描述 -->
      <view class="form-block">
        <text class="block-title">描述</text>
        <textarea
          class="description-textarea"
          placeholder="请输入任务描述"
          v-model="task.description"
          :maxlength="-1"
        ></textarea>
      </view>

      <!-- 附件 -->
      <view class="form-block">
        <text class="block-title">附件</text>
        <view class="attachment-list">
          <view 
            v-for="(file, index) in task.attachments" 
            :key="index" 
            class="attachment-item"
          >
            <view class="attachment-icon">
              <text class="i-fa-solid:file"></text>
            </view>
            <view class="attachment-info">
              <text class="attachment-name">{{ file.name }}</text>
              <text class="attachment-size">{{ file.size }}</text>
            </view>
            <text class="attachment-delete i-fa-solid:times" @click="removeAttachment(index)"></text>
          </view>
          <view class="add-attachment" @click="addAttachment">
            <text class="add-icon i-fa-solid:plus"></text>
            <text class="add-text">添加附件</text>
          </view>
        </view>
      </view>

      <!-- 删除按钮 -->
      <view v-if="isEdit" class="delete-button" @click="confirmDelete">
        <text>删除任务</text>
      </view>
    </scroll-view>

    <!-- 分类选择器 -->
    <view v-if="showCategorySelector" class="popup-overlay" @click="showCategorySelector = false">
      <view class="popup-container" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择分类</text>
          <text class="popup-close" @click="showCategorySelector = false">取消</text>
        </view>
        <view class="popup-content">
          <view
            v-for="(category, index) in categories"
            :key="index"
            class="popup-item"
            @click="selectCategory(category)"
          >
            <view
              class="category-tag"
              :style="{
                backgroundColor: getCategoryBgColor(category),
                color: getCategoryColor(category),
              }"
            >
              {{ category }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 优先级选择器 -->
    <view v-if="showPrioritySelector" class="popup-overlay" @click="showPrioritySelector = false">
      <view class="popup-container" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择优先级</text>
          <text class="popup-close" @click="showPrioritySelector = false">取消</text>
        </view>
        <view class="popup-content">
          <view
            v-for="(priority, index) in priorities"
            :key="index"
            class="popup-item"
            @click="selectPriority(priority.value)"
          >
            <view class="priority-select-item">
              <view :class="['priority-dot', {
                'priority-high': priority.value === 'high',
                'priority-medium': priority.value === 'medium',
                'priority-low': priority.value === 'low'
              }]"></view>
              <text class="priority-label">{{ priority.label }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期选择器 -->
    <view v-if="showDatePicker" class="popup-overlay" @click="showDatePicker = false">
      <view class="popup-container" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择日期</text>
          <text class="popup-close" @click="showDatePicker = false">取消</text>
        </view>
        <view class="popup-content">
          <picker
            mode="date"
            :value="task.date || formatDate(new Date())"
            @change="onDateChange"
            class="date-picker"
          >
            <view class="picker-view">
              <text>{{ task.date || '请选择日期' }}</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 时间选择器 -->
    <view v-if="showTimePicker" class="popup-overlay" @click="showTimePicker = false">
      <view class="popup-container" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择时间</text>
          <text class="popup-close" @click="showTimePicker = false">取消</text>
        </view>
        <view class="popup-content">
          <view class="time-picker-container">
            <picker mode="time" :value="startTime" @change="onStartTimeChange" class="time-picker">
              <view class="picker-view">
                <text>{{ startTime || '开始时间' }}</text>
              </view>
            </picker>
            <text class="time-separator">至</text>
            <picker mode="time" :value="endTime" @change="onEndTimeChange" class="time-picker">
              <view class="picker-view">
                <text>{{ endTime || '结束时间' }}</text>
              </view>
            </picker>
          </view>
          <button class="confirm-button" @click="confirmTimeRange">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'TaskEditPage',
})

import { taskService } from '@/services/task-service'
import { dbService } from '@/services/database'
import type { Task } from '@/services/task-service'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 是否为编辑模式
const isEdit = ref(false)
// 任务ID参数
const taskId = ref('')
// 是否正在加载或保存
const loading = ref(false)
// 是否禁用保存按钮（防抖）
const saveDisabled = ref(false)

// 分类列表
const categories = ref<string[]>([])

// 加载分类列表
const loadCategories = async () => {
  try {
    const categoryList = await taskService.getTaskCategories()
    categories.value = categoryList.map(c => c.name)
  } catch (error) {
    console.error('加载分类列表失败:', error)
    // 使用默认分类列表作为后备
    categories.value = ['工作', '个人', '学习', '生活', '其他']
  }
}

// 优先级列表
const priorities = ref([
  { label: '高优先级', value: 'high', dotClass: 'bg-red-500' },
  { label: '中优先级', value: 'medium', dotClass: 'bg-orange-500' },
  { label: '低优先级', value: 'low', dotClass: 'bg-green-500' },
])

// 弹窗状态
const showCategorySelector = ref(false)
const showPrioritySelector = ref(false)
const showDatePicker = ref(false)
const showTimePicker = ref(false)

// 时间选择
const startTime = ref('')
const endTime = ref('')

// 任务数据
const task = ref<Task>({
  id: '',
  title: '',
  category: '',
  priority: 'medium',
  date: '',
  timeRange: '',
  completed: false,
  reminder: true,
  description: '',
  attachments: [] as { name: string; size: string }[],
  createdAt: '',
  updatedAt: ''
})

// 获取分类的背景色
const getCategoryBgColor = (category: string) => {
  switch (category) {
    case '工作':
      return 'rgba(255, 87, 34, 0.1)'
    case '个人':
      return 'rgba(33, 150, 243, 0.1)'
    case '购物':
      return 'rgba(76, 175, 80, 0.1)'
    case '学习':
      return 'rgba(156, 39, 176, 0.1)'
    case '家庭':
      return 'rgba(255, 193, 7, 0.1)'
    default:
      return 'rgba(158, 158, 158, 0.1)'
  }
}

// 获取分类的文字颜色
const getCategoryColor = (category: string) => {
  switch (category) {
    case '工作':
      return '#ff5722'
    case '个人':
      return '#2196f3'
    case '购物':
      return '#4caf50'
    case '学习':
      return '#9c27b0'
    case '家庭':
      return '#ffc107'
    default:
      return '#9e9e9e'
  }
}

// 获取任务优先级文本
const getPriorityText = (priority: string) => {
  switch (priority) {
    case 'high':
      return '高优先级'
    case 'medium':
      return '中优先级'
    case 'low':
      return '低优先级'
    default:
      return '中优先级'
  }
}

// 切换提醒状态
const toggleReminder = (e: any) => {
  task.value.reminder = e.detail.value
}

// 选择分类
const selectCategory = (category: string) => {
  task.value.category = category
  showCategorySelector.value = false
}

// 选择优先级
const selectPriority = (priority: string) => {
  task.value.priority = priority
  showPrioritySelector.value = false
}

// 日期改变
const onDateChange = (e: any) => {
  const date = new Date(e.detail.value)
  task.value.date = formatDate(date)
  showDatePicker.value = false
}

// 开始时间改变
const onStartTimeChange = (e: any) => {
  startTime.value = e.detail.value
}

// 结束时间改变
const onEndTimeChange = (e: any) => {
  endTime.value = e.detail.value
}

// 确认时间范围
const confirmTimeRange = () => {
  if (startTime.value && endTime.value) {
    task.value.timeRange = `${startTime.value} - ${endTime.value}`
  } else if (startTime.value) {
    task.value.timeRange = startTime.value
  }
  showTimePicker.value = false
}

// 添加附件
const addAttachment = () => {
  uni.chooseFile({
    count: 1,
    success: (res) => {
      const file = res.tempFiles[0]
      const size = formatFileSize(file.size)
      task.value.attachments.push({
        name: file.name,
        size,
      })
    },
  })
}

// 移除附件
const removeAttachment = (index: number) => {
  task.value.attachments.splice(index, 1)
}

// 确认删除
const confirmDelete = () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除此任务吗？此操作无法撤销。',
    success: (res) => {
      if (res.confirm) {
        deleteTask()
      }
    },
  })
}

// 删除任务
const deleteTask = async () => {
  if (!task.value.id) return

  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个任务吗？此操作无法撤销。',
    success: async (res) => {
      if (res.confirm) {
        loading.value = true
        try {
          const success = await taskService.deleteTask(task.value.id)
          if (success) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            })
            setTimeout(() => {
              goBack()
            }, 1500)
          } else {
            throw new Error('删除失败')
          }
        } catch (error) {
          console.error('删除任务失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none',
          })
        } finally {
          loading.value = false
        }
      }
    }
  })
}

// 保存任务
const saveTask = async (retryCount = 0) => {
  // 防抖处理
  if (saveDisabled.value || loading.value) {
    return;
  }
  
  // 验证必填字段
  if (!task.value.title) {
    uni.showToast({
      title: '请输入任务标题',
      icon: 'none',
    })
    return
  }

  // 防抖锁定
  saveDisabled.value = true;
  setTimeout(() => {
    saveDisabled.value = false;
  }, 2000);

  // 显示加载状态
  uni.showLoading({
    title: retryCount > 0 ? `保存中(第${retryCount}次尝试)...` : '保存中...',
    mask: true
  });
  
  loading.value = true;
  
  try {
    // 组合时间范围
    if (startTime.value) {
      task.value.timeRange = startTime.value
      if (endTime.value) {
        task.value.timeRange += ' - ' + endTime.value
      }
    }
    
    // 处理分类信息，将分类名称转换为分类ID
    if (task.value.category) {
      // 获取所有任务分类
      const categories = await taskService.getTaskCategories();
      
      // 查找匹配的分类
      const matchedCategory = categories.find(c => c.name === task.value.category);
      
      if (matchedCategory) {
        // 使用找到的分类ID
        task.value.categoryId = matchedCategory.id;
      } else {
        // 如果找不到匹配的分类，使用默认分类
        const defaultCategory = await dbService.getDefaultCategory('task');
        if (defaultCategory) {
          task.value.categoryId = defaultCategory.id;
        }
      }
    }

    console.log(`准备保存任务(第${retryCount}次尝试):`, {
      id: task.value.id,
      title: task.value.title,
      category: task.value.category,
      categoryId: task.value.categoryId,
      priority: task.value.priority
    });

    // 尝试保存任务
    const success = await taskService.saveTask(task.value);

    // 隐藏加载状态
    uni.hideLoading();
    loading.value = false;

    if (success) {
      // 显示成功提示
      uni.showToast({
        title: isEdit.value ? '更新成功' : '创建成功',
        icon: 'success',
        duration: 1500
      });
      
      // 保存成功后返回上一页
      setTimeout(() => {
        goBack();
      }, 1500);
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    // 隐藏加载状态
    uni.hideLoading();
    loading.value = false;
    
    console.error('保存任务出错:', error);
    
    // 如果是初次保存失败或重试次数较少，自动重试
    const maxRetries = 3;
    if (retryCount < maxRetries) {
      console.log(`自动重试保存任务(${retryCount + 1}/${maxRetries})...`);
      
      // 显示正在重试的提示
      uni.showToast({
        title: `正在重试(${retryCount + 1}/${maxRetries})...`,
        icon: 'none',
        duration: 1000
      });
      
      // 延迟后自动重试
      setTimeout(() => {
        saveTask(retryCount + 1);
      }, 1500);
      return;
    }
    
    // 如果重试次数用尽，显示错误提示
    let errorMessage = '无法保存任务，请稍后再试。';
    
    uni.showModal({
      title: '保存失败',
      content: errorMessage,
      showCancel: true,
      cancelText: '取消',
      confirmText: '重试',
      success: (res) => {
        if (res.confirm) {
          // 用户点击重试，再次尝试保存
          setTimeout(() => {
            saveTask(0);  // 重置重试计数
          }, 1000);
        }
      }
    });
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 格式化日期
const formatDate = (date: Date) => {
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + 'B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + 'KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + 'MB'
  }
}

// 页面加载
onLoad(async (options) => {
  // 加载分类列表
  await loadCategories()
  
  if (options && options.id) {
    isEdit.value = true
    taskId.value = options.id
    
    // 加载任务详情
    loading.value = true
    try {
      const taskData = await taskService.getTaskById(taskId.value)
      if (taskData) {
        task.value = taskData
        
        // 处理时间范围
        if (task.value.timeRange) {
          const times = task.value.timeRange.split(' - ')
          startTime.value = times[0]
          endTime.value = times[1] || ''
        }
        
        // 如果有分类信息，设置category字段
        if (task.value.category) {
          task.value.category = task.value.category.name
        } else if (task.value.categoryId) {
          // 如果只有categoryId没有category对象，查找对应的分类名称
          const categories = await taskService.getTaskCategories()
          const category = categories.find(c => c.id === task.value.categoryId)
          if (category) {
            task.value.category = category.name
          }
        }
      } else {
        throw new Error('任务不存在')
      }
    } catch (error) {
      console.error('加载任务详情失败:', error)
      uni.showToast({
        title: '加载任务失败',
        icon: 'none',
      })
      setTimeout(() => {
        goBack()
      }, 1500)
    } finally {
      loading.value = false
    }
  }
})
</script>

<style lang="scss">
.task-edit-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.custom-nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  background-color: #ffffff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.nav-left {
  display: flex;
  align-items: center;
}

.nav-icon {
  font-size: 20px;
  margin-right: 10px;
  color: #333;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.nav-right {
  display: flex;
  align-items: center;
}

.nav-save {
  font-size: 16px;
  color: #007aff;
  font-weight: 500;
}

.nav-disabled {
  opacity: 0.5;
}

.task-edit-content {
  flex: 1;
  padding: 16px;
}

.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  margin-bottom: 10px;
  background-color: #ffffff;
  border-radius: 10px;
}

.form-label {
  font-size: 16px;
  color: #333;
  width: 80px;
}

.form-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.form-input {
  flex: 1;
  text-align: right;
  font-size: 16px;
}

.form-arrow {
  font-size: 14px;
  color: #c7c7cc;
  margin-left: 8px;
}

.placeholder-text {
  color: #c7c7cc;
  font-size: 16px;
}

.category-tag {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 14px;
}

.priority-item {
  display: flex;
  align-items: center;
}

.priority-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
}

.priority-high {
  background-color: #ff3b30;
}

.priority-medium {
  background-color: #ff9500;
}

.priority-low {
  background-color: #34c759;
}

.priority-text {
  font-size: 16px;
  color: #333;
}

.date-text, .time-text {
  font-size: 16px;
  color: #333;
}

.form-block {
  margin-bottom: 20px;
}

.block-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 10px;
  padding-left: 8px;
}

.description-textarea {
  width: 100%;
  height: 100px;
  background-color: #ffffff;
  border-radius: 10px;
  padding: 16px;
  font-size: 16px;
}

.attachment-list {
  background-color: #ffffff;
  border-radius: 10px;
  overflow: hidden;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.attachment-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background-color: rgba(0, 122, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #007aff;
}

.attachment-info {
  flex: 1;
}

.attachment-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
  display: block;
}

.attachment-size {
  font-size: 13px;
  color: #8e8e93;
  display: block;
}

.attachment-delete {
  font-size: 18px;
  color: #8e8e93;
  padding: 10px;
}

.add-attachment {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
}

.add-icon {
  font-size: 18px;
  color: #8e8e93;
  margin-right: 8px;
}

.add-text {
  font-size: 16px;
  color: #8e8e93;
}

.delete-button {
  margin-top: 30px;
  background-color: #ff3b30;
  color: #ffffff;
  border-radius: 10px;
  text-align: center;
  padding: 16px;
  font-size: 16px;
}

.popup-overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 100;
  display: flex;
  align-items: flex-end;
}

.popup-container {
  width: 100%;
  background-color: #ffffff;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.popup-close {
  font-size: 16px;
  color: #007aff;
}

.popup-content {
  padding: 16px;
  max-height: 60vh;
  overflow-y: auto;
}

.popup-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.popup-item:last-child {
  border-bottom: none;
}

.priority-select-item {
  display: flex;
  align-items: center;
}

.priority-label {
  font-size: 16px;
  color: #333;
}

.date-picker, .time-picker {
  width: 100%;
}

.picker-view {
  background-color: #f5f5f5;
  padding: 12px;
  text-align: center;
  border-radius: 10px;
  font-size: 16px;
}

.time-picker-container {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.time-separator {
  margin: 0 10px;
  font-size: 16px;
  color: #333;
}

.time-picker {
  flex: 1;
}

.confirm-button {
  background-color: #007aff;
  color: #ffffff;
  border-radius: 10px;
  padding: 12px;
  font-size: 16px;
  width: 100%;
  text-align: center;
}
</style>
